package com.pxdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pxdp.dto.LoginFormDTO;
import com.pxdp.dto.Result;
import com.pxdp.dto.UserDTO;
import com.pxdp.entity.User;
import com.pxdp.mapper.UserMapper;
import com.pxdp.service.IUserService;
import com.pxdp.utils.RedisConstants;
import com.pxdp.utils.RegexUtils;
import com.pxdp.utils.SystemConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public Result getCode(String phone, HttpSession session) {
        if(RegexUtils.isPhoneInvalid(phone)){
            return Result.fail("手机号格式有误");
        }

        //随机生成验证码
        String code = RandomUtil.randomNumbers(6);


        //将验证码存储到redis中
        stringRedisTemplate.opsForValue().set(RedisConstants.LOGIN_CODE_KEY+phone,code,RedisConstants.LOGIN_CODE_TTL, TimeUnit.MINUTES);

        log.info("短信发送成功，验证短信：{}",code);

        return Result.ok();
    }

    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        //获取前端传来的用户手机号信息
        String phone = loginForm.getPhone();
        //判断手机号格式
        if(RegexUtils.isPhoneInvalid(phone)){
            return Result.fail("手机号格式有误");
        }
        //从redis中提取用户信息
        String code = stringRedisTemplate.opsForValue().get(RedisConstants.LOGIN_CODE_KEY + phone);
        String userCode = loginForm.getCode();
        //判断用户传来的验证码与redis中存储的是否一致
        if(code == null || !code.equals(userCode)){
            return Result.fail("验证码错误");
        }
        //查询数据库里的用户
        User user = query().eq("phone", phone).one();
        //如果用户不存在，直接新建用户
        if(user == null){
            user = creatUser(phone);
        }
        //将用户信息存储到redis中
         //首先生成随机token作为登录令牌
        String token = UUID.randomUUID().toString();
         //将user对象转换成hashMap存储
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        Map<String, Object> map = BeanUtil.beanToMap(userDTO,new HashMap<>(), CopyOptions.create().setIgnoreNullValue(true).setFieldValueEditor((name,value) ->{return value.toString();}));

        //存储到redis中
        stringRedisTemplate.opsForHash().putAll(RedisConstants.LOGIN_USER_KEY+token,map);
        //设置存储时间
        stringRedisTemplate.expire(RedisConstants.LOGIN_USER_KEY+token,RedisConstants.LOGIN_USER_TTL, TimeUnit.SECONDS);
        //返回给前端token
        return Result.ok(token);
    }

    private User creatUser(String phone) {

        User user = new User();

        user.setPhone(phone);

        user.setNickName(SystemConstants.USER_NICK_NAME_PREFIX + RandomUtil.randomString(6));

        save(user);
        return user;
    }
}
